package com.bawei.lib_common.vm

import android.util.Log
import androidx.lifecycle.ViewModel
import com.bawei.lib_common.intent.BaseViewIntent
import com.bumptech.glide.util.Executors
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.newSingleThreadContext

/**
 * 基础viewmodel类
 */
abstract class BaseViewModel<I:BaseViewIntent>:ViewModel() {

    val channel: Channel <I> =  Channel(Channel.UNLIMITED)

    private val exceptionHander= CoroutineExceptionHandler { coroutineContext, throwable ->
        Log.e("Viewmodel", "ViewModel发生异常:"+throwable.message)

    }

    //自定义携程作用域
    protected val mViewModelScope= CoroutineScope(Dispatchers.Main+ SupervisorJob()+exceptionHander)

    //自定义调度器
    val mDingleThreadDispatcher= newSingleThreadContext("SingleThreadDispatcher")
    val mFixedThreadDispatcher= newFixedThreadPoolContext(32,"FixedThread")

    //使用Excutors创建线程池的方式来创建调度器
    val mDispatcher=java.util.concurrent.Executors.newFixedThreadPool(16).asCoroutineDispatcher()


    init {
        mViewModelScope.launch {
            channel.receiveAsFlow().collect {
                dispatchIntent(it)
            }
        }
    }

    abstract fun dispatchIntent(intent: I)
}